package com.example.demo1122.filter;

import com.example.demo1122.domain.LoginAdmin;
import com.example.demo1122.domain.LoginStudent;
import com.example.demo1122.domain.LoginTeacher;
import com.example.demo1122.utils.JwtUtil;
import com.example.demo1122.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        //获取请求url
        String requestURI = request.getRequestURI();
        if (!StringUtils.hasText(token)) {
            if ("/student/login".equals(requestURI) || "/teacher/login".equals(requestURI) || "/admin/login".equals(requestURI)) {
                //放行
                filterChain.doFilter(request, response);
                return;
            }
            throw new RuntimeException("缺少认证令牌");
        }

        //解析token
        String userID = null;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            if ((Integer) claims.get("role") == 1){
                userID = claims.get("studentID").toString();
                //从redis中获取用户信息
                String redisKey = "studentlogin:" + userID;
                LoginStudent loginStudent = redisCache.getCacheObject(redisKey);
                if(Objects.isNull(loginStudent)){
                    throw new RuntimeException("用户未登录");
                }
                //存入SecurityContextHolder
                //TODO 获取权限信息封装到Authentication中
                Collection<? extends GrantedAuthority> authorities = loginStudent.getAuthorities();

                UsernamePasswordAuthenticationToken authenticationToken =
                        new UsernamePasswordAuthenticationToken(loginStudent,null,authorities);
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
            if ((Integer) claims.get("role") == 2){
                userID = claims.get("teacherID").toString();
                //从redis中获取用户信息
                String redisKey = "teacherlogin:" + userID;
                LoginTeacher loginTeacher = redisCache.getCacheObject(redisKey);
                if(Objects.isNull(loginTeacher)){
                    throw new RuntimeException("用户未登录");
                }
                //存入SecurityContextHolder
                //TODO 获取权限信息封装到Authentication中
                Collection<? extends GrantedAuthority> authorities = loginTeacher.getAuthorities();

                UsernamePasswordAuthenticationToken authenticationToken =
                        new UsernamePasswordAuthenticationToken(loginTeacher,null,authorities);
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
            if ((Integer) claims.get("role") == 3){
                userID = claims.get("adminID").toString();
                //从redis中获取用户信息
                String redisKey = "adminlogin:" + userID;
                LoginAdmin loginAdmin = redisCache.getCacheObject(redisKey);
                if(Objects.isNull(loginAdmin)){
                    throw new RuntimeException("用户未登录");
                }
                //存入SecurityContextHolder
                //TODO 获取权限信息封装到Authentication中
                // 从 LoginAdmin 类中获取权限信息
                Collection<? extends GrantedAuthority> authorities = loginAdmin.getAuthorities();

                UsernamePasswordAuthenticationToken authenticationToken =
                        new UsernamePasswordAuthenticationToken(loginAdmin,null,authorities);
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
//            userid = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        //放行
        filterChain.doFilter(request, response);
    }
}

